package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.entity.dto.DishDto;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired(required = false)
    private DishService dishService;

    @PostMapping
    public R save(@RequestBody DishDto dishDto, HttpSession session){
        dishDto.setCreateUser((Long) session.getAttribute("employee"));
        dishDto.setUpdateUser((Long) session.getAttribute("employee"));
        dishService.save(dishDto);
        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R page(@RequestParam(defaultValue = "1") Integer page,
                  @RequestParam(defaultValue = "10") Integer pageSize,
                  String name){
        Page<DishDto> dtoPage = dishService.getByPage(page, pageSize, name);
        return R.success(dtoPage);
    }

    @GetMapping("/{id}")
    public R detail(@PathVariable Long id, HttpSession session){
        DishDto dishDto = dishService.getById(id);
        return R.success(dishDto);
    }

    @PutMapping
    public R update(@RequestBody DishDto dishDto,HttpSession session){
        dishDto.setUpdateTime(LocalDateTime.now());
        dishDto.setUpdateUser((Long) session.getAttribute("employee"));

        dishService.updateDish(dishDto);
        return R.success("修改成功");
    }

    @GetMapping("/list")
    public R list(Long categoryId, Integer status){
        List<DishDto> dishList = dishService.getByCategoryId(categoryId, status);
        return R.success(dishList);
    }
}
